// index.js
// 获取应用实例
const app = getApp()
import mqtt from '../../utils/js/mqtt.min.js'; // 加载mqtt库

Page({
  data: {
    uid: "d542e726e7594ade9022b7b9bf97c063", // 用户密钥，巴法云控制台获取
    ledtopic: "led002", // 控制led的主题，mqtt控制台创建
    dhttopic: "temp004", // 传输温湿度的主题，控制台创建
    moldytopic: "moldy004", // 传输发霉的主题，控制台创建
    dishstopic: "dishs004", // 接收菜品推荐的主题
    ledOnOff: "关闭",
    moldy: "未知",
    checked: false, // led的状态。默认led关闭
    wendu: "", // 温度值，默认为空
    shidu: "", // 湿度值，默认为空
    ledicon: "/utils/img/lightoff.png", // 显示led图标的状态。默认是关闭状态图标
    client: null, // mqtt客户端，默认为空
    dishs: [], // 存储推荐菜式列表
  },

  mqttConnect() {
    var that = this;

    // MQTT连接的配置
    var options = {
      keepalive: 60, // 60s ，表示心跳间隔
      clean: true, // cleanSession不保持持久会话
      protocolVersion: 4, // MQTT v3.1.1
      clientId: this.data.uid
    };

    // 初始化mqtt连接
    this.data.client = mqtt.connect('wxs://bemfa.com:9504/wss', options);

    // 连接mqtt服务器
    this.data.client.on('connect', function () {
      console.log('连接服务器成功');
      // 订阅dht11温湿度主题
      that.subscribeTopic(that.data.dhttopic);
      // 订阅菜品推荐主题
      that.subscribeTopic(that.data.dishstopic);
      // 订阅发霉状态主题
      that.subscribeTopic(that.data.moldytopic);
    });

    // 接收消息
    that.data.client.on('message', function (topic, message) {
      console.log(topic);
      var msg = message.toString();
      if (topic == that.data.dhttopic) { // 如果是温湿度主题的消息
        that.handleDHTMessage(msg);
      } else if (topic == that.data.dishstopic) { // 如果是菜品推荐主题的消息
        that.handleDishMessage(msg);
      } else if (topic == that.data.moldytopic) { // 如果是发霉状态主题的消息
        that.handleMoldyMessage(msg);
      }
      // 打印消息
      console.log('收到消息：' + msg);
    });

    // 断线重连
    this.data.client.on("reconnect", function () {
      console.log("重新连接");
    });
  },

  subscribeTopic(topic) {
    this.data.client.subscribe(topic, function (err) {
      if (err) {
        console.error(`订阅 ${topic} 失败:`, err);
      } else {
        console.log(`订阅 ${topic} 成功`);
      }
    });
  },

  handleDHTMessage(msg) {
    if (msg.indexOf("#") != -1) { // 如果数据里包含#号，表示获取的是传感器值
      var all_data_arr = msg.split("#"); // 分割数据，并把分割后的数据放到数组里。
      console.log(all_data_arr); // 打印数组
      if (all_data_arr.length >= 4 && all_data_arr[3] != undefined) { // 判断是否上传了led状态
        this.setData({
          ledOnOff: all_data_arr[3] === "on" ? "打开" : "关闭",
          ledicon: all_data_arr[3] === "on" ? "/utils/img/lighton.png" : "/utils/img/lightoff.png",
          checked: all_data_arr[3] === "on"
        });
      }
      this.setData({
        wendu: all_data_arr[1],
        shidu: all_data_arr[2],
      });
    }
  },

  handleDishMessage(msg) {
    var dishs = msg.split(", "); // 假设消息是以逗号分隔的菜品名称列表
    this.setData({
      dishs: dishs // 更新推荐菜式列表
    });
  },

  handleMoldyMessage(msg) {
    this.setData({
      moldy: msg.trim() // 去除多余空格
    });
  },

  // 屏幕打开时执行的函数
  onLoad() {
    // 连接mqtt
    this.mqttConnect();

    // 确保MQTT连接成功后再进行其他操作
    const checkConnection = setInterval(() => {
      if (this.data.client && this.data.client.connected) {
        clearInterval(checkConnection);
        this.getDHTData();
        this.getMoldyData();
        this.getDishes();
      }
    }, 1000); // 每秒检查一次连接状态
  },

  // 控制灯的函数1，小滑块点击后执行的函数
  onChange({ detail }) {
    this.setData({
      ledOnOff: detail ? "打开" : "关闭",
      ledicon: detail ? "/utils/img/lighton.png" : "/utils/img/lightoff.png",
      checked: detail
    });
    this.data.client.publish(this.data.ledtopic, detail ? 'on' : 'off');
  },

  // 点击led图片执行的函数
  onChange2() {
    this.onChange({ detail: !this.data.checked });
  },

  getDataFromServer(topic) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://api.bemfa.com/api/device/v1/data/3/get/',
        data: {
          uid: this.data.uid,
          topic: topic,
          num: 1
        },
        header: {
          'content-type': "application/x-www-form-urlencoded"
        },
        success: (res) => {
          resolve(res.data.data);
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  },

  async getDHTData() {
    try {
      const data = await this.getDataFromServer(this.data.dhttopic);
      if (data && data.length > 0) {
        const msg = data[0].msg;
        if (msg.indexOf("#") != -1) {
          const all_data_arr = msg.split("#");
          this.setData({
            wendu: all_data_arr[1],
            shidu: all_data_arr[2],
            ledOnOff: all_data_arr[3] === "on" ? "打开" : "关闭",
            ledicon: all_data_arr[3] === "on" ? "/utils/img/lighton.png" : "/utils/img/lightoff.png",
            checked: all_data_arr[3] === "on"
          });
        }
      }
    } catch (err) {
      console.error("获取温湿度数据失败:", err);
    }
  },

  async getMoldyData() {
    try {
      const data = await this.getDataFromServer(this.data.moldytopic);
      if (data && data.length > 0) {
        const msg = data[0].msg;
        this.setData({
          moldy: msg.trim() // 去除多余空格
        });
      }
    } catch (err) {
      console.error("获取发霉数据失败:", err);
    }
  },

  async getDishes() {
    try {
      const data = await this.getDataFromServer(this.data.dishstopic);
      if (data && data.length > 0) {
        const msg = data[0].msg;
        const dishs = msg.split(", ");
        this.setData({
          dishs: dishs
        });
      }
    } catch (err) {
      console.error("获取菜品推荐信息失败:", err);
    }
  }
});



